import React, {useEffect, useState} from 'react';
import ProForm, {ProFormText} from "@ant-design/pro-form";
import {Form, message, Modal, Skeleton, Space, TreeSelect} from "antd";
import {updatePermission, showPermission} from "@/services/permission";

const Create = (props) => {
  const {isModalVisible, isShowModal, treeData, actionRef, permissionId} = props
  const [initialValues, setInitialValues] = useState(undefined);
  const [value, setValue] = useState(undefined);

  useEffect(async () => {
    // 发送请求，获取权限详情
    const response = await showPermission(permissionId)
    setInitialValues({
      pid: parseInt(response.data.pid),
      name: response.data.name,
      cn_name: response.data.cn_name
    })
  }, [])

  /**
   * 修改权限
   * @param values
   */
  const createPermission = async values => {
    if (values.pid === 0) {
      values.pid = '';
    }
    // 发送请求，更新用户
    const response = await updatePermission(permissionId, values)
    if (response.status === undefined) {
      message.success('修改成功')
      // 刷新表格数据
      actionRef.current.reload()
      // 关闭模态框
      isShowModal(false)
    }
  }

  return (
    <div>
      <Modal
        title="修改权限"
        footer={null}
        centered={true}
        visible={isModalVisible}
        onCancel={() => isShowModal(false)}
        destroyOnClose={true}
      >
        {
          !initialValues ?
            <div>
              <Skeleton.Input style={{ width: 328,marginBottom:28 }} active={true} />
              <Skeleton.Input style={{ width: 328,marginBottom:28 }} active={true} />
              <Skeleton.Input style={{ width: 328,marginBottom:28 }} active={true} />
              <Skeleton.Input style={{ width: 328,marginBottom:28 }} active={true} /><br/>
              <Skeleton.Button style={{ width: 100,marginBottom:28 }} active={true} />
              <Skeleton.Button style={{ width: 100,marginLeft:28 }} active={true} />
            </div>
          :
          <ProForm
            initialValues={initialValues}
            onFinish={values => createPermission(values)}
          >
            <Form.Item name="pid" label="父级权限">
              <TreeSelect
                treeData={treeData}
                style={{width: 328}}
                placeholder="父级部门"
                rules={[{required: true, message: '请选择父级权限'}]}
              />
            </Form.Item>
            <ProFormText width="md" name="name" label="路由地址"
                         rules={[{required: true, message: '请输入路由地址'}]}
                         placeholder="请输入路由地址"/>
            <ProFormText width="md" name="cn_name" label="权限名称"
                         rules={[{required: true, message: '请输入权限名称'}]}
                         placeholder="请输入权限名称"/>
          </ProForm>}
      </Modal>
    </div>
  );
};

export default Create;
